import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2023-01-02
 * Time:21:28
 */
@WebServlet("/blog_delete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断用户的登陆状态
        HttpSession session=req.getSession(false);
        if(session==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登录");
            return;
        }
        User user =(User)session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登录");
            return;
        }
        //获取blogId
        String blogId=req.getParameter("blogId");
        if(blogId==null){
            resp.setStatus(404);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前要删除的blogId有误");
            return;
        }
        //查询blogId对应的blog对象
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
        if(blog==null){
            resp.setStatus(404);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前要删除的blog不存在");
            return;
        }
        //判定登录的是本人
        if(blog.getUserId()!=user.getUserId()){
            //博客的作者///////会话的作者
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("您不能删除不是您的博客");
            return;
        }
        //开始删除
        blogDao.delete(Integer.parseInt(blogId));
        //重定向
        resp.sendRedirect("blog.html");
    }
}
